#define _BSD_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <string.h>

#define MAXSIZE 256

static int read_and_parse (FILE *stream, char *retbuf)
{
char buffer [MAXSIZE];

if (fgets (buffer , MAXSIZE , stream)== NULL) {
	if (feof (stream)) {
		fprintf (stderr ," EOF !\n");
		return-1;
	} else if ( ferror ( stream)) {
		fprintf (stderr ," ERR !\n");
		return-1;
	}
}
/* Eliminer le CR de fin de chaine */
	buffer [ strlen ( buffer)-1] ='\0';
	snprintf ( retbuf , MAXSIZE ,"%s" , buffer);
	return 0;
}

static void init_surv (fd_set *s)
{
	FD_ZERO (s);
	FD_SET (fileno (stdin) ,s);
	return ;
}

int w (int argc , char *argv []) {
	FILE *stream;
	fd_set readt;
	int retval;
	char retbuf [MAXSIZE];
	int num_desc ;
	
	if ( argc !=2) {
		fprintf ( stderr ," NO FD\n");
		exit ( EXIT_FAILURE);
	}

	num_desc = atoi ( argv [1]);
	
	if ( num_desc <=0) {
		fprintf ( stderr," BAD FILENO !\n");
		exit ( EXIT_FAILURE);
	}

	if (( stream = fdopen ( num_desc ,"w")) == NULL) {
		fprintf ( stderr ," BAD FD !\n");
		exit ( EXIT_FAILURE);
	}

	init_surv (& readt);

	while (1) {
		select (fileno (stdin)+1 , & readt , NULL , NULL , NULL);
		if ( FD_ISSET ( fileno ( stdin) , & readt)) {
			retval = read_and_parse ( stdin , retbuf);
			if ( retval < 0) {
				exit ( EXIT_FAILURE);
			}
			fprintf ( stream ,"%s\n", retbuf);
			fflush (stream);
		}
		init_surv (&readt);
	}
}
